package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Quarantine;
import com.antdesignbackend.backend.entity.entityVo.QuarantineVo;
import com.antdesignbackend.backend.service.QuarantineService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.util.*;

@RequestMapping("/quarantineDeclaration")
@Controller
public class QuarantineDeclarationController extends BaseController {

    @Autowired
    QuarantineService quarantineService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer menuId;

    @GetMapping("/index")
    @AuthToken
    public String ProductionIndex(String menuId) {
        this.menuId = Integer.parseInt(menuId);
        return "quarantineDeclaration/index";
    }

    /**
     * 分页查询
     * @param
     * @return
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
        public ReturnVO tableSearch(@RequestBody QuarantineVo quarantineVo) {
        ReturnVO result = new ReturnVO();
        List<Quarantine> datalist=new ArrayList<>();
        try {
            QueryWrapper<Quarantine> queryWrapper = new QueryWrapper<>();
            if (quarantineVo.getApplicant() != null && !quarantineVo.getApplicant().equals(""))
                queryWrapper.like("applicant",quarantineVo.getApplicant());
            if (quarantineVo.getReportType() != null && !quarantineVo.getReportType().equals(""))
                queryWrapper.eq("reportType",quarantineVo.getReportType());
            if (quarantineVo.getTimeInterval() != null && !quarantineVo.getTimeInterval().equals("")){
                String[] str=quarantineVo.getTimeInterval().split(" - ");
                String star=str[0];
                String end=str[1];
                queryWrapper.between("reportDate",star,end);
            }
            queryWrapper.orderByDesc("reportDate");
            queryWrapper.eq("eid",getLoginEnterpriseId());
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=quarantineService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist=quarantineService.page(new Page<>(quarantineVo.getPageIndex(),quarantineVo.getPageSize()),queryWrapper).getRecords();
                for(Quarantine quarantine:datalist){
                    quarantine.setHttpLivestockPhoto(WebConfig.host+"images/"+quarantine.getLivestockPhoto());
                    quarantine.setHttpCarPhoto(WebConfig.host+"images/"+quarantine.getCarPhoto());
                }
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    @PostMapping("/tableSearchMe/{eid}")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearchMe(@PathVariable("eid") int eid) {
        ReturnVO result = new ReturnVO();
        List<Quarantine> datalist=new ArrayList<>();
        try {
            QueryWrapper<Quarantine> queryWrapper = new QueryWrapper<>();
            QuarantineVo quarantineVo=new QuarantineVo();
            queryWrapper.eq("eid",eid);
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=quarantineService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist=quarantineService.page(new Page<>(quarantineVo.getPageIndex(),quarantineVo.getPageSize()),queryWrapper).getRecords();
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    /**
     * 修改/新增操作的保存
     */
    @PostMapping("/save")
    @ResponseBody
    @AuthToken
    public ReturnVO save(@RequestBody Quarantine quarantine) throws Exception {
        ReturnVO result = new ReturnVO();
        boolean b = false;
        if(quarantine.getQuarantineId()==null || quarantine.getQuarantineId()==0){
            quarantine.setUid(getLoginUserId());
            quarantine.setEid(getLoginEnterpriseId());
            quarantine.setReportDate(new Date());
            quarantine.setApplicant(getLoginEnterpriseName());
            b=quarantineService.save(quarantine);
        }else{
            b=quarantineService.updateById(quarantine);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }
        else
        {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /**
     * 删除
     * @param
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        ReturnVO result = new ReturnVO();
        if (quarantineService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
        } else {
            result.setMessage("删除失败");
            result.setCode("0");
        }
        return result;
    }
    /***
     * 上传图片
     * @return
     */
    @PostMapping("/uploadImages")
    @ResponseBody
    public Map<String,String> uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8") ;
        long random =System.currentTimeMillis();
        String dateKey =random+"";
        String localPathDir="";
        String newFileName="";
        Map<String,String> map = new HashMap<>();
        if(!WebConfig.uploadImage.equals(""))
        {
            localPathDir=WebConfig.uploadImage;
        }
        else
        {
            localPathDir= ResourceUtils.getURL("classpath:").getPath()+"images/";
        }
        File logoSaveFile = new File(localPathDir);
        if(!logoSaveFile.exists()){
            logoSaveFile.mkdirs();
        }
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
            Iterator iter = mr.getFileMap().values().iterator();
            if (iter.hasNext()) {
                MultipartFile file = (MultipartFile) iter.next();
                String oname = file.getOriginalFilename();
                String fileTyle=oname.substring(oname.lastIndexOf("."),oname.length());
                fileTyle=fileTyle.toLowerCase();
                newFileName=dateKey+fileTyle;
                String fileName = localPathDir+newFileName;
                if(fileTyle.equals(".png") || fileTyle.equals(".gif") || fileTyle.equals(".jpg"))
                {
                    File files = new File(fileName);
                    InputStream inputstream =file.getInputStream();
                    byte[] bytes = new byte[1024];
                    FileOutputStream outstream = new FileOutputStream(fileName);
                    int index;
                    while ((index = inputstream.read(bytes)) != -1) {
                        outstream.write(bytes, 0, index);
                        outstream.flush();
                    }
                    outstream.close();
                    inputstream.close();
                }
            }
        }
        if(newFileName!=null && !newFileName.equals(""))
        {
            map.put("url",newFileName);
            map.put("httpUrl",WebConfig.host+"images/"+newFileName);
        }
        // System.out.println("return:"+localPathDir+newFileName);
        return map;
    }
}

